layui.use(['form','jquery','table','layer','upload'],function() {
    var form = layui.form
        ,$ = layui.jquery
        ,table = layui.table
        ,layer = layui.layer
        ,upload = layui.upload;


    //导入课程
    //拖拽上传
    upload.render({
         elem: '#test10'
        ,auto: true
        ,url: '/course/importExcel'
        ,accept: 'file'
        ,field: 'file'
        ,done: function(res){
            layer.msg('上传成功');
        }
    });
    excel = function excel(){
        layer.open({
            type:1,
            title:'拖拽文件',
            content:$('#test10'),
            area:['350px','300px'],
            offser:'auto',
            shade:0.4
        });
    }


    //获取当前时间
    var newTime;
    getTime();
    function getTime(){
        var myDate = new Date();
        var myYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
        var myMonth = myDate.getMonth()+1; //获取当前月份(0-11,0代表1月)
        var myToday = myDate.getDate(); //获取当前日(1-31)
        var myDay = myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
        var myHour = myDate.getHours(); //获取当前小时数(0-23)
        var myMinute = myDate.getMinutes(); //获取当前分钟数(0-59)
        var mySecond = myDate.getSeconds(); //获取当前秒数(0-59)
        newTime = myYear+'-'+myMonth+'-'+myToday+' '+myHour+':'+myMinute+':'+mySecond;
    };

    //获取当前用户信息
    var updateBy = JSON.parse(localStorage.getItem("user")).trueName;

    //添加操作日志函数
    function addoperationLog(data){
        $.ajax({
            url: '/course/addoperationLog'
            ,data: data
            ,dataType: 'json'
            ,success:function(data){
            }
        });
    }


    /*表格数据行内操作-------------------------*/
    //查看
    see = function see(id){

        //添加操作日志
        var log = {
             'dictSort': 4
            ,'updateBy': updateBy
            ,'updateTime': newTime
            ,'remark': '执行了查询操作'
        }
        addoperationLog(log);

        $('#parentId').val(id);
        layer.open({
            type: 2
            ,content: 'popup/course-see.html'
            ,title: '课程详情'
            ,area: ['950px','500px']
            ,btn: ['关闭']
            ,yes:function (index) {
                layer.close(index);
            }
        });
    }

    //编辑
    edit = function edit(id){

        $('#parentId').val(id);
        layer.open({
            type: 2
            ,content: 'popup/course-edit.html'
            ,area: ['950px','470px']
            ,end:function () {
                refresh();
                var cao = '周五';
                var ni = '度过';
                var ma = '美好';
                var de = '的';
            }

        });
    }

    //日志
    journal = function journal(){
        //location.href = '/course/course-journal.html';
        layer.open({
             type: 2
            ,title: '课程历史价格'
            ,content: 'popup/course-journalPopup.html'
            ,area: ['1100px','700px']
            ,btn:['关闭']
            ,yes:function(index){
                 layer.close(index);
            }
        });

    }

    //删除
    del = function del(id){
        layer.open({
             type: 0
            ,title: '删除课程'
            ,content: '您确定删除除此课程吗？'
            ,btn: ['确定','取消']
            ,yes:function(index){
                $.ajax({
                    url: '/course/delCourse'
                    ,data: {'courseId': id}
                    ,dataType: 'json'
                    ,success:function (data) {
                        if(data.data){
                            //添加操作日志
                            var log = {
                                'dictSort': 2
                                ,'updateBy': updateBy
                                ,'updateTime': newTime
                                ,'remark': '执行了删除操作'
                            }
                            addoperationLog(log);
                            refresh();
                            layer.msg('删除成功');
                        }
                    }
                });
                layer.close(index);
            }
        })

    }

    //审核详情
    auditDetails = function auditDetails(id){
        $('#parentId').val(id);
        layer.open({
             type: 2
            ,title: '审核详情'
            ,content: 'popup/course-AuditDetails.html'
            ,area: ['700px','500px']
            ,btn: ['关闭']
            ,yes:function (index) {
                layer.close(index);
            }
        });

    }




    //返回
    backOff = function backOff() {
        var arr = localStorage.getItem("numArr");
        var numArr = arr.split(",");
        numArr.pop();
        window.parent.layui.element.tabChange('tab',numArr[numArr.length - 1]);
        localStorage.setItem("numArr",numArr);
    }
    //刷新
    refresh = function refresh(){
        window.location.reload();
    }


    /*普通检索--------------------*/
    //搜索
    search = function search(){
        var courseName = $('input[name=courseName]').val();
        var name = $('select[name=name]').val();
        var trueName = $('select[name=trueName]').val();
        var courseLabel = $('select[name=courseLabel]').val();
        var object = {
            'courseName': courseName
            ,'name': name
            ,'trueName': trueName
            ,'courseLabel': courseLabel
        }
        $.ajax({
            url: '/course/ordinarySearch'
            ,data: object
            ,dataType: 'json'
            ,success:function (data) {
                tableRender(data.data);
            }
        });
    }
    //重置
    reset = function reset(){
        $('input[name=courseName]').val('');
        $('select[name=classId]').val('0');
        $('select[name=tureName]').val('0');
        $('select[name=courseLabel]').val('0');

    }




    /*高级检索---------------------*/
    //弹出层
    advancedRetrieval = function advancedRetrieval(){
        layer.open({
            type: 2
            ,title: '高级检索'
            ,content: 'popup/advancedRetrieval.html'
            ,area: ['650px','360px']
        });
    }




    /*添加课程-----------------------------*/
    addCourse = function addCourse(){
        window.location.href ='course-list-add.html';
    }







    /*table -----------------------------------------------------------------------*/
    //获取默认展示数据
    $.ajax({
        url: '/course/getCourse'
        ,data: {'classId': 2}
        ,dateType: 'json'
        ,success: function(data){
            tableRender(data.data);
        }
    });

    //监听数据节点展示对应分类数据请求
    function getClassCourse(classId){
        $.ajax({
            url: '/course/getCourse'
            ,data: {'classId': classId}
            ,dateType: 'json'
            ,success: function(data){
                tableRender(data.data);
            }
        });
    }
    //表格渲染
    tableRender = function tableRender(data){
        table.render({
            elem: '#table'
            ,toolbar:'#toolutil'
            ,data: data
            ,page: true
            ,cols: [[
                {checkbox: true}
                ,{type: 'numbers',title: '编号',align:'center'}
                ,{field: 'url',title: '课程推片',align:'center',templet:function(data){
                        return '<img src="'+data.url+'"/>'
                    }}
                ,{field: 'courseName',title: '课程名称',align:'center'}
                ,{field: 'courseNprice',title: '价格',align:'center'}
                ,{field: 'userId',title: '上传人员',align:'center'}
                ,{field: 'name',title: '分类',align:'center'}
                ,{field: 'coursePrimary',title: '标签',align:'center'}
                ,{field: 'saleNum',title: '销量',align:'center'}
                ,{field: 'courseStatus',title: '上架/下架',align: 'center',templet:function(data){
                    if(data.courseStatus == 2){
                         return '<input type="checkbox" name="courseStatus" value="'+data.courseId+'" lay-filter="sx" lay-skin="switch" lay-text="上架|下架" checked>'
                    }else if(data.courseStatus == 3){
                        return '<input type="checkbox" name="courseStatus" value="'+data.courseId+'" lay-filter="sx" lay-skin="switch" lay-text="上架|下架">'
                    }else{
                        return '后台数据错误'
                    }
                }}
                ,{field: 'courseCstatus',title: '审核状态',align:'center',templet:function (data) {
                        if(data.courseCstatus == '3'){
                            return '<p>未审核</p><br/>' +
                                '<a style="color: #0DAB9E;" href="#" onclick="auditDetails('+data.courseId+')">审核详情</a>';
                        }else if(data.courseCstatus == '4'){
                            return '<p>审核中</p><br/>' +
                                '<a style="color: #0DAB9E;" href="#" onclick="auditDetails('+data.courseId+')">审核详情</a>';
                        }else if(data.courseCstatus == '5'){
                            return '<p>审核失败</p><br/>' +
                                '<a style="color: #0DAB9E;" href="#" onclick="auditDetails('+data.courseId+')">审核详情</a>';
                        }else{
                            return '<p>其他</p><br/>' +
                                '<a style="color: #0DAB9E;" href="#" onclick="auditDetails('+data.courseId+')">审核详情</a>';
                        }
                    }}
                ,{field: '',title: '操作',align:'center',templet:function (data) {
                        return '<a style="color: #0DAB9E;" onclick="see('+data.courseId+')">查看</a>  <a style="color: #0DAB9E;" onclick="edit('+data.courseId+')">编辑</a><br/><br/>' +
                            '<a style="color: #0DAB9E;" onclick="journal()">日志</a>  <a style="color: #0DAB9E;" onclick="del('+data.courseId+')">删除</a>'
                    }}
            ]]
        });
    }

    //监听上架下架开关
    form.on('switch(sx)',function(obj){
        var checked = obj.elem.checked;
        var courseId = obj.value;
        if(checked){
            var courseStatus = 2;
        }else{
            var courseStatus = 3;
        }

        $.ajax({
             url: '/course/setCourseStatus'
            ,data: {
                 'courseStatus':courseStatus
                ,'courseId': courseId
            }
            ,dataType: 'json'
            ,success:function(data){
                 if(data.data){
                     if(checked){
                         layer.msg('上架成功');
                     }else{
                         layer.msg('已下架');
                     }
                 }
            }
        })

    });





    /*ztree -----------------------------------------------------------------------*/
    //获取数据
    zTreeAjax();
    function zTreeAjax(){
        $.ajax({
            url: '/course/getCourseClass'
            ,dataTyope: 'json'
            ,success: function (data) {
                zNodes(data.data);
            }
        });
    }
    //ztree函数
    function zNodes(data) {
        //settingss
        var settingss = {
            data: {
                simpleData: {
                    enable: true //true 、 false 分别表示 使用 、 不使用 简单数据模式
                    ,idKey: "id"  //节点数据中保存唯一标识的属性名称
                    ,pIdKey: "parentId"    //节点数据中保存其父节点唯一标识的属性名称
                    ,rootPId: -1 //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                }
                ,key: {
                    name: "title"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                }
            }
            ,check: {
                enable: true   //true 、 false 分别表示 显示 、不显示 复选框或单选框
                ,nocheckInherit: true //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
            }
            ,callback: {
                 onClick : zTreeOnClick//点击节点触发
                ,onRightClick: zTreeRigthClick//右键节点之后触发
            }
        }

        function zTreeRigthClick(event, treeId, treeNode){
            if(treeNode.id != null){
                if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                    showRMenu("root", event.clientX, event.clientY,treeNodes);
                } else if (treeNode && !treeNode.noR) {
                    showRMenu("node", event.clientX, event.clientY,treeNode);
                    a=treeNode.id
                }
            }
        }

        //显示右键菜单
        function showRMenu(type, x, y,treeNode) {
            $("#rMenu ul").show();
            $(rMenu).css({"top":y+"px", "left":x+"px", "visibility":"visible"}); //设置右键菜单的位置、可见
            $("body").bind("mousedown", onBodyMouseDown);
            $('input[name=nodeId]').val(treeNode.id);
            $('input[name=NodeParentId]').val(treeNode.parentId);
        }

        //隐藏右键菜单
        function hideRMenu() {
            $(rMenu).css({"visibility": "hidden"}); //设置右键菜单不可见
        }

        //鼠标点击菜单时调用
        function onBodyMouseDown(event) {
            if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
                $(rMenu).css({ "visibility" : "hidden"});
            }
        }

        //添加
        newNode = function newNode(){
            var parentId = $('input[name=nodeId]').val();
            layer.open({
                 type: 0
                ,title: '添加节点'
                ,content: '<input type="text" id="nodeName" placeholder="输入新的节点名称" class="layui-input">'
                ,btn: ['确定','取消']
                ,yes:function (index) {
                    var name = $('#nodeName').val();
                    var data = {
                        'parentId': parentId
                        ,'title': name
                        ,'create_id': updateBy
                        ,'create_date': newTime
                        ,'update_id': updateBy
                        ,'update_date': newTime
                        ,'remarks': '添加节点'
                        ,'type': 1
                    }

                    $.ajax({
                         url: '/course/addZtreeNode'
                         ,data: data
                         ,dataType: 'json'
                         ,success:function(data){
                            if(data.data){
                                layer.msg('添加成功');
                            }
                         }
                     });
                    layer.close(index)
                }
                ,btn2:function (index) {
                    layer.close(index)
                }
                ,end:function () {
                    zTreeAjax();
                }
            })




        }

        //修改
        editNode = function(){
            var id = $('input[name=nodeId]').val();
            layer.open({
                 type: 0
                ,title: '修改节点'
                ,content: '<input type="text" id="nodeName" placeholder="输入新的节点名称" class="layui-input">'
                ,btn: ['确定','取消']
                ,yes:function (index) {
                    var name = $('#nodeName').val();
                    var data = {
                         'id': id
                        ,'title': name
                    }
                    $.ajax({
                        url: '/course/editZtreeNode'
                        ,data: data
                        ,dataType: 'json'
                        ,success:function(data){
                            if(data.data){
                                layer.msg('修改成功');
                            }
                        }
                    });
                     layer.close(index)
                }
                ,btn2:function (index) {
                    layer.close(index)
                }
                ,end:function () {
                    zTreeAjax();
                }
            })

        }

        //删除
        delNode = function () {
            var id = $('input[name=nodeId]').val();
            layer.open({
                type: 0
                ,title: '删除节点'
                ,content: '您是否要删除此节点？'
                ,btn: ['确定','取消']
                ,yes:function (index) {
                    var data = {
                        'id': id
                    }
                    $.ajax({
                        url: '/course/delZtreeNode'
                        ,data: data
                        ,dataType: 'json'
                        ,success:function(data){
                            if(data.data){
                                layer.msg('删除成功');
                            }
                        }
                    });
                    layer.close(index)
                }
                ,btn2:function (index) {
                    layer.close(index)
                }
                ,end:function () {
                    zTreeAjax();
                }
            })
        }

        //点击节点事件函数
        function zTreeOnClick(event,treeId,treeNode){
            //请求java课程数据
            if(treeNode.id == '2'){
                getClassCourse(treeNode.id);
                return;
            }else if(treeNode.id == '3'){
                //请求spring课程数据
                getClassCourse(treeNode.id);
                return;
            }else if(treeNode.id == '4'){
                //请求spring课程数据
                getClassCourse(treeNode.id);
                return;
            }else if(treeNode.id == '5'){
                //请求spring课程数据
                getClassCourse(treeNode.id);
                return;
            }else if(treeNode.id == '7'){
                //请求spring课程数据
                getClassCourse(treeNode.id);
                return;
            }else if(treeNode.id == '8'){
                //请求spring课程数据
                getClassCourse(treeNode.id);
                return;
            }else if(treeNode.id == '9'){
                //请求spring课程数据
                getClassCourse(treeNode.id);
                return;
            }
        }
        //部署
        zTreeObj = $.fn.zTree.init($("#zTreeDemo"), settingss, data); //初始化树
        zTreeObj.expandAll(true);    //true 节点全部展开、false节点收缩
    }








});